// pages/home/home.js
const app = getApp()
const isCollectTag = app.globalData.isCollect
Page({

    /**
     * 页面的初始数据
     */
    data: {
        item: 0,
        tab: 0,
        state: 'paused',
        // 播放的索引值
        playIndex: 0,
        playlist: [],
        collectList: [],
        playingList: [],
        isCollectTag: isCollectTag
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function () {
        //获取音乐列表
        wx.request({
            url: 'https://www.walkman.asia:2023/music/list',
            success: (res) => {
                this.setData({
                    playlist: res.data
                })
                wx.setStorageSync('collected', res.data)
                console.log(this.data.playlist)
            }
        })
        const userId = wx.getStorageSync('login_key').user_id
        //获取收藏列表
        wx.request({
            url: `https://www.walkman.asia:2023/list/collect/${userId}`,
            success: (res) => {
                console.log(res)
                this.setData({
                    collectList: res.data
                })
                console.log(this.data.collectList)
                this.addCollected()
                console.log(this.data.playlist)
            }
        })
    },

    audioCtx: null,
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        this.audioCtx = wx.createInnerAudioContext()
        //默认选中第1曲
        // this.setMusic(0)
        //播放完成切换下一曲
        var that = this
        this.audioCtx.onEnded(function () {
            that.next()
        })
        // 自动更新播放进度
        this.audioCtx.onPlay(function () {})
        this.audioCtx.onTimeUpdate(function () {
            that.setData({
                'play.duration': formatTime(that.audioCtx.duration),
                'play.currentTime': formatTime(that.audioCtx.currentTime),
                'play.percent': that.audioCtx.currentTime / that.audioCtx.duration * 100
            })
        })

        function formatTime(time) {
            var minute = Math.floor(time / 60) % 60;
            var second = Math.floor(time) % 60
            return (minute < 10 ? '0' + minute : minute) + ':' + (second < 10 ? '0' + second : second)
        }
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        console.log(app.globalData.isCollect)
        this.setData({
            isCollectTag: app.globalData.isCollect
        })
        if (this.data.isCollectTag == true) {
            this.collectPlay()
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },
    //给音乐列表添加收藏属性
    addCollected: function () {
        for (var i = 0; i < this.data.collectList.length; i++) {
            for (var j = 0; j < this.data.playlist.length; j++) {
                if (this.data.playlist[j].music_id == this.data.collectList[i].music_id) {
                    this.data.playlist[j].collected = true
                } else {
                    this.data.playlist[j].collected = false
                }
            }
        }
    },

    changeItem: function (e) {
        this.setData({
            item: e.target.dataset.item
        })
    },
    // tab切换
    changeTab: function (e) {
        this.setData({
            tab: e.detail.current
        })
    },
    player: function () {
        this.setData({
            tab: 1,
            item: 1
        })
    },
    setMusic: function (index) {
        var playinglist = this.data.playingList[index]
        const playingUrl = (playinglist.singer + '-' + playinglist.music_name).replace(/\s*/g, "")
        this.audioCtx.src = `https://www.walkman.asia:2023/getMusic/all/${playingUrl}.mp3`
        this.setData({
            state: 'running',
            playIndex: index,
            'playing.title': playinglist.music_name,
            'playing.singer': playinglist.singer,
            'playing.coverImgUrl': `https://www.walkman.asia:2023/getPhoto/music_pic/${playinglist.music_pic}`,
            'play.currentTime': '00:00',
            'play.duration': '00:00',
            'play.percent': 0,
            collected: playinglist.collected
        })
    },
    play: function () {
        this.audioCtx.play()
        this.setData({
            state: 'running'
        })
    },
    pause: function () {
        this.audioCtx.pause()
        this.setData({
            state: 'paused'
        })
    },
    before: function () {
        var index = this.data.playingList.length <= 1 ? 0 : this.data.playIndex - 1
        this.setMusic(index)
        if (this.data.state == 'running') {
            this.play()
        }
    },
    next: function () {
        var index = this.data.playingList.length <= 1 ? 0 : this.data.playIndex + 1
        this.setMusic(index)
        if (this.data.state == 'running') {
            this.play()
        }
    },
    // 滚动条调节歌曲进度
    sliderChange: function (e) {
        var second = e.detail.value * this.audioCtx.duration / 100
        this.audioCtx.seek(second)
    },
    // 播放列表换曲功能
    change: function (e) {
        this.setMusic(e.currentTarget.dataset.index)
        this.play()
    },
    //上传功能
    upload: function () {
        wx.navigateTo({
            url: '/pages/upload/upload',
        })
    },
    //下载列表
    downloadList: function () {
        wx.navigateTo({
            url: '/pages/downloadList/downloadList',
        })
    },
    //收藏列表
    collectList: function () {
        wx.navigateTo({
            url: '/pages/collect/collect',
        })
    },

    //推荐歌曲点击在播放器中播放并放入播放列表
    playing: function (e, index) {
        var playinglist = ''
        console.log(e)
        var index = e.currentTarget.id - 1
        playinglist = this.data.playlist[index]

        const playingUrl = (playinglist.singer + '-' + playinglist.music_name).replace(/\s*/g, "")
        this.audioCtx.src = `https://www.walkman.asia:2023/getMusic/all/${playingUrl}.mp3`
        this.play()

        const playingList = this.data.playingList
        playingList.push(playinglist)
        this.setData({
            playingList: playingList
        })
        this.setData({
            'playing.title': playinglist.music_name,
            'playing.singer': playinglist.singer,
            'playing.coverImgUrl': `https://www.walkman.asia:2023/getPhoto/music_pic/${playinglist.music_pic}`,
            'playing.music_id': playinglist.music_id,
            'play.currentTime': '00:00',
            'play.duration': '00:00',
            'play.percent': 0,
            collected: playinglist.collected,
            playIndex: index
        })
        console.log(this.data.playingList)
    },
    collectPlay: function () {
        var playinglist = wx.getStorageSync('collectPlay')
        const playingUrl = (playinglist.singer + '-' + playinglist.music_name).replace(/\s*/g, "")
        this.audioCtx.src = `https://www.walkman.asia:2023/getMusic/all/${playingUrl}.mp3`
        this.play()

        const playingList = this.data.playingList
        playingList.push(playinglist)
        this.setData({
            playingList: playingList
        })
        this.setData({
            'playing.title': playinglist.music_name,
            'playing.singer': playinglist.singer,
            'playing.coverImgUrl': `https://www.walkman.asia:2023/getPhoto/music_pic/${playinglist.music_pic}`,
            'playing.music_id': playinglist.music_id,
            'play.currentTime': '00:00',
            'play.duration': '00:00',
            'play.percent': 0,
            collected: playinglist.collected,
            playIndex: playinglist.music_id-1
        })
    },
    //播放页下载功能
    download: function () {
        wx.setStorageSync('downloadUrl', this.audioCtx.src)
        wx.showModal({
            title: '下载歌曲',
            content: '复制以下链接至浏览器下载歌曲' + this.audioCtx.src,
            showCancel: true,
            cancelText: "否", //默认是“取消”
            cancelColor: 'skyblue', //取消文字的颜色
            confirmText: "是", //默认是“确定”
            confirmColor: 'skyblue', //确定文字的颜色
            success: function (res) {
                console.log(res)
                if (res.cancel) {

                } else {
                    wx.navigateTo({
                        url: '/pages/download/download',
                    })
                }
            }
        })
    },
    //播放页收藏功能
    collect: function () {
        const musicId = this.data.playing.music_id
        const userId = wx.getStorageSync('login_key').user_id
        console.log(musicId)
        console.log(userId)
        wx.request({
            url: 'https://www.walkman.asia:2023/music/collect',
            method: 'POST',
            data: {
                music_id: musicId,
                user_id: userId
            },
            success: (res) => {
                console.log(res)
                this.setData({
                    'playing.collected': true
                })
            }
        })
    },
    delCollect: function () {
        const musicId = this.data.playing.music_id
        const userId = wx.getStorageSync('login_key').user_id
        console.log(musicId)
        console.log(userId)
        wx.request({
            url: 'https://www.walkman.asia:2023/music/del_collect',
            method: 'POST',
            data: {
                music_id: musicId,
                user_id: userId
            },
            success: (res) => {
                console.log(res)
                this.setData({
                    'playing.collected': false
                })
            }
        })
    }
})